package com.example.project.activity.wode;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.activity.kaishi.LoginActivity;
import com.example.project.activity.mingxi.HistoryActivity;
import com.example.project.bean.YearDetail;
import com.example.project.dialog.BeiZhuDialog;
import com.example.project.dialog.BudgetDialog;
import com.example.project.dialog.UpdateNameDialog;
import com.example.project.utils.PhotoPopupWindow;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.UUID;

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener{
    int mainId;
    String mainIds;
    ImageView iv_head,iv_back;
    TextView tv_id,tv_name,tv_eamil;
    RelativeLayout rl_head,rl_name;
    Button bt_quit;
    SharedPreferences preferences; //共享参数
    PhotoPopupWindow mPhotoPopupWindow;

    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_SMALL_IMAGE_CUTTING = 2;
    private static final int REQUEST_BIG_IMAGE_CUTTING = 3;
    private static final String IMAGE_FILE_NAME = "icon.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        init();
    }

    private void init() {
        mainId= MyApplication.getMainId(); //获取用户信息
        mainIds=mainId+"";
        volleyExport(mainIds);
        iv_back=findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        bt_quit=findViewById(R.id.bt_quit);
        bt_quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logOut();
                Intent intent=new Intent( UserInfoActivity.this, LoginActivity.class );
                startActivity( intent );
            }
        });
        iv_head=findViewById(R.id.iv_head);
        tv_id=findViewById(R.id.tv_id);
        tv_id.setText(mainId+"");
        tv_name=findViewById(R.id.tv_name);
        tv_eamil=findViewById(R.id.tv_eamil);

        rl_head=findViewById(R.id.rl_head);
        rl_head.setOnClickListener(this);
        rl_name=findViewById(R.id.rl_name);
        rl_name.setOnClickListener(this);
    }
    //退出登录
    private void logOut(){
        File file= new File("/data/data/"+getPackageName().toString()+"/shared_prefs","QQ.xml");
        if(file.exists()){
            file.delete();
            Toast.makeText(this, "退出成功", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_head:
                mPhotoPopupWindow = new PhotoPopupWindow(UserInfoActivity.this, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 进入相册选择
                                mPhotoPopupWindow.dismiss();
                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image/*");
                                // 判断系统中是否有处理该 Intent 的 Activity
                                if (intent.resolveActivity(getPackageManager()) != null) {
                                    startActivityForResult(intent, REQUEST_IMAGE_GET);
                                } else {
                                    Toast.makeText(UserInfoActivity.this, "未找到图片查看器", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 拍照
                                mPhotoPopupWindow.dismiss();
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                            }
                        });
                        View rootView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.activity_main, null);
                        mPhotoPopupWindow.showAtLocation(rootView,
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                break;

            case R.id.rl_name:
                showBZDialog();
                break;
        }
    }


    /**
     * 处理回调结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调成功
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                // 小图切割
                case REQUEST_SMALL_IMAGE_CUTTING:
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;

                // 相册选取
                case REQUEST_IMAGE_GET:
                    try {
                        startSmallPhotoZoom(data.getData());
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                    break;

                // 拍照
                case REQUEST_IMAGE_CAPTURE:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);
                    startSmallPhotoZoom(Uri.fromFile(temp));
                    break;
            }
        }

    }
    /**
     * 小图模式切割图片
     * 此方式直接返回截图后的 bitmap，由于内存的限制，返回的图片会比较小
     */
    public void startSmallPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300); // 输出图片大小
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_SMALL_IMAGE_CUTTING);
    }

    /**
     * 小图模式中，保存图片后，设置到视图中
     */
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data"); // 直接获得内存中保存的 bitmap
            // 创建 smallIcon 文件夹
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String storage = Environment.getExternalStorageDirectory().getPath();
                File dirFile = new File(storage + "/smallIcon");
                if (!dirFile.exists()) {
                    if (!dirFile.mkdirs()) {
                        Log.e("TAG", "文件夹创建失败");
                    } else {
                        Log.e("TAG", "文件夹创建成功");
                    }
                }
                File file = new File(dirFile, System.currentTimeMillis() + ".jpg");
                // 保存图片
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 在视图中显示图片
            iv_head.setImageBitmap(photo);
        }
    }

    /**
     * 大图模式切割图片
     * 直接创建一个文件将切割后的图片写入
     */
    public void startBigPhotoZoom(Uri uri) {
        // 创建大图文件夹
        Uri imageUri = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String storage = Environment.getExternalStorageDirectory().getPath();
            File dirFile = new File(storage + "/bigIcon");
            if (!dirFile.exists()) {
                if (!dirFile.mkdirs()) {
                    Log.e("TAG", "文件夹创建失败");
                } else {
                    Log.e("TAG", "文件夹创建成功");
                }
            }
            File file = new File(dirFile, System.currentTimeMillis() + ".jpg");
            imageUri = Uri.fromFile(file);
        }
        // 开始切割
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 600); // 输出图片大小
        intent.putExtra("outputY", 600);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false); // 不直接返回数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // 返回一个文件
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, REQUEST_BIG_IMAGE_CUTTING);
    }


    //弹出修改姓名对话框
    protected void showBZDialog(){
        final UpdateNameDialog dialog=new UpdateNameDialog( UserInfoActivity.this );
        dialog.show(); //显示弹窗
        dialog.setDialogSize(); //动态设置弹窗大小
        dialog.setOnEnsureListener( new UpdateNameDialog.OnEnsureListener() {
            @Override
            public void onEnsure() {
                String msg=dialog.getEditText(); //将备注的信息获取出来
                if(!TextUtils.isEmpty( msg )){ //如果为空，就还剩设置为空的
                    volleyUpdateName(msg,mainIds);
                    tv_name.setText( msg );
                }
                dialog.cancel(); //废除对话框，才能进行activity销毁
            }
        } );

    }

    //返现数据
    public void volleyExport( String mainIds) {
        VolleyRequest.RequesetPost(ConstantUtil.USERINFO, "UserInfo", Params.GetString(mainIds), new VolleyInterface(this) {

            @Override
            public void onMySuccess(String result) throws JSONException {
                System.out.println("result:"+result);
                JSONObject jsonObject = null;
                jsonObject =new JSONObject( result );
                String username=jsonObject.getString( "username" );
                String img=jsonObject.getString( "img" );
                String eamil=jsonObject.getString( "eamil" );
                tv_name.setText(username);
                tv_eamil.setText(eamil);
                iv_head.setImageResource(Integer.parseInt(img));
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(UserInfoActivity.this,"网络不好！！！",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });

    }

    //更新名字
    private void volleyUpdateName(String name,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.UPDATENAME, "UpdateName", Params.GetString2(name,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr)  {
                if(!jsonStr.equals("1")){
                    Toast.makeText(UserInfoActivity.this, "数据库出错", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(UserInfoActivity.this, "更新失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

}